package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.itheima.mapper.StudentMapper;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Student;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@CrossOrigin(origins = {"*","null"})
public class Controller {
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserMapper userMapper;
    private Gson gson = new Gson();

    @GetMapping("/students")
    public String gerStudents(){
        List<Student> students=studentMapper.selectList(null);
        return gson.toJson(students);
    }
    @PostMapping("/add")
    public void addStudent(@RequestBody Student student){
        studentMapper.insert(student);
    }
    @PostMapping("/delete")
    public void deleteStudent(@RequestBody Student student){
        studentMapper.deleteById(student);
    }
    @PostMapping("/update")
    public void updateStudent(@RequestBody Student student){
        studentMapper.updateById(student);
    }
    @PostMapping("/login")
    public String login(@RequestBody User user){
        QueryWrapper<User> userQueryWrapper= new QueryWrapper<>();
        userQueryWrapper.setEntity(user);
        User user1=userMapper.selectOne(userQueryWrapper);
        if(user1!=null){
            return "0";
        }
        return "1";
    }
    @PostMapping("/register")
    public void register(@RequestBody User user){
        userMapper.insert(user);
    }
    @PostMapping("/search")
    public String search(@RequestBody HashMap<String,String> data){
        String name=data.get("name");
        QueryWrapper<Student> studentQueryWrapper=new QueryWrapper<>();
        studentQueryWrapper.like("name",name);
        List<Student> students=studentMapper.selectList(studentQueryWrapper);
        return gson.toJson(students);
    }
}
